package per.dg.multiprocesskotlin.messenger

import android.app.Service
import android.content.Intent
import android.os.*
import android.util.Log

class MessengerService : Service() {

    private val TAG = "MessengerService"

    override fun onBind(intent: Intent): IBinder {
        return mMessenger.binder
    }

    private val mMessengerHandler : Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what){
                MESSAGE_FROM_CLIENT -> {
                    Log.e(TAG, "receive message from client:" + msg.getData().getString("msg"))
                    mMessengerClient = msg.replyTo

                    sendDataToClient()
                }
                else ->{
                    super.handleMessage(msg)
                }
            }
        }
    }

//    服务器端 Messenger
    private val mMessenger : Messenger = Messenger(mMessengerHandler)

//    客户端 Messenger
    lateinit private var mMessengerClient : Messenger

    /**
     * 发送数据到客户端
     */
    fun sendDataToClient(){
        val msg: Message = Message.obtain(null, MESSAGE_FROM_SERVICE)
        val bundle = Bundle()
        bundle.putString("msg", "hello client, I have received your message!")
        msg.data = bundle
        try {
            mMessengerClient.send(msg)
        } catch (e: RemoteException) {
            e.printStackTrace()
        }
    }
}